﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using WebBHXH.Entities;
using System.IO;
using System.Data;
using GemBox.Spreadsheet;

namespace WebBHXH
{
    public partial class DotBH : System.Web.UI.Page
    {
        List<MaDotBHModel> listMaDotBHModel;
        DataTable datatable;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GetData("1");
                GetLoaiBHModel();
                GetDonViBHModel();
                GetTinhModel();
            }
        }

        private void GetData(string flag)
        {
            System.Net.WebRequest request = null;
            if(flag == "1")
            {
                request = System.Net.WebRequest.Create(""+Util.getUrl() + "Home/GetMaDotBHModel");
            } 
            else
            {
                request = System.Net.WebRequest.Create(""+Util.getUrl() + "Home/SearchMaDotBHModel?donVi=" + ddlDonViBH.SelectedValue + "&tinh=" + ddlTinh.SelectedValue + "&doiTuong=" + txtObject.Text + "&loaiBH=" + ddlLoaiBH.SelectedValue);
            }
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json; charset=utf-8";
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            //get response-stream, and use a streamReader to read the content
            listMaDotBHModel = new List<MaDotBHModel>();
            using (Stream s = request.GetResponse().GetResponseStream())
            {
                using (StreamReader sr = new StreamReader(s))
                {
                    JavaScriptSerializer jsonserializer = new JavaScriptSerializer();
                    listMaDotBHModel = jsonserializer.Deserialize<List<MaDotBHModel>>(sr.ReadToEnd());
                    datatable = getDataTable();
                    DataRow row;
                    List<string> listString = GetListNamColumn();
                    foreach (MaDotBHModel maDotBHModel in listMaDotBHModel)
                    {
                            row = datatable.NewRow();
                            row["MaDotBH"] = maDotBHModel.MaDotBH;
                            row["DonViBH"] = maDotBHModel.DonViBH;
                            row["MaTinh"] = maDotBHModel.MaTinh;
                            row["Huyen"] = maDotBHModel.Huyen;
                            row["DoiTuong"] = maDotBHModel.DoiTuong;
                            row["NgayLap"] = maDotBHModel.NgayLap.ToShortDateString();
                            row["LoaiBH"] = maDotBHModel.LoaiBH;
                            row["MucBH"] = maDotBHModel.MucBH;
                            row["SoTien1Nam"] = maDotBHModel.SoTien1Nam;
                            row["NguoiSudung"] = maDotBHModel.NguoiSudung;
                            row["NgayTaoMoi"] = maDotBHModel.NgayTaoMoi.ToShortDateString();
                            row["NgayCapNhat"] = maDotBHModel.NgayCapNhat.ToShortDateString();

                            datatable.Rows.Add(row);
                    }

                    GridView1.DataSource = datatable;
                    GridView1.DataBind();
                }
            }
        }

        private void GetTinhModel()
        {
            List<TinhModel> listTinhModel = new TinhModel().GetTinhModel();
            foreach (TinhModel tinhModel in listTinhModel)
            {
                ddlTinh.Items.Add(tinhModel.MaTinh);
            }
        }

        private void GetDonViBHModel()
        {
            List<DonViBHModel> listDonViBHModel = new DonViBHModel().GetDonViBHModel();
            foreach (DonViBHModel donViBHModel in listDonViBHModel)
            {
                ddlDonViBH.Items.Add(donViBHModel.MaDonViBH);
            }
        }

        public List<string> GetListNamColumn()
        {
            List<string> listStr = new List<string>();
            listStr.Add("MaDotBH");
            listStr.Add("DonViBH");
            listStr.Add("MaTinh");
            listStr.Add("Huyen");
            listStr.Add("DoiTuong");
            listStr.Add("NgayLap");
            listStr.Add("LoaiBH");
            listStr.Add("MucBH");
            listStr.Add("SoTien1Nam");
            listStr.Add("NguoiSudung");
            listStr.Add("NgayTaoMoi");
            listStr.Add("NgayCapNhat");
            return listStr;
        }

        public DataTable getDataTable()
        {
            DataTable myTable = new DataTable("DotBH");
            DataColumn column;
            List<string> listString = GetListNamColumn();
            foreach (var item in listString)
            {
                column = new DataColumn();
                column.DataType = System.Type.GetType("System.String");
                column.ColumnName = item;
                column.ReadOnly = false;
                myTable.Columns.Add(column);
            }

            return myTable;
        }

        private void GetLoaiBHModel()
        {
            List<LoaiBHModel> listLoaiBHModel = new LoaiBHModel().GetLoaiBHModel();
            foreach (LoaiBHModel loaiBHModel in listLoaiBHModel)
            {
                ddlLoaiBH.Items.Add(loaiBHModel.MaLoaiBH);
            }
        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string id = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
            Response.Redirect("AddDotBH.aspx?Id=" + id);
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            string id = GridView1.Rows[e.RowIndex].Cells[1].Text;
            System.Net.WebRequest request = System.Net.WebRequest.Create(""+Util.getUrl() + "Home/deleteDotBaoHiem?id=" + id);
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/json; charset=utf-8";
            //get response-stream, and use a streamReader to read the content
            Stream s = request.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(s);
            string result = sr.ReadToEnd();
            if (result == "200")
            {
                //Label1.Text = "ok";
            }
            else
            {
                //Label1.Text = "error";
            }
            GetData("1");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            GetData("2");
        }

        public void export()
        {
            // Create excel file.
            ExcelFile ef = new ExcelFile();
            ExcelWorksheet ws = ef.Worksheets.Add("DataSheet");
            ws.InsertDataTable(datatable, "A1", true);
            Response.Clear();
            string excel = "XLS";

            // Stream file to browser, in required type.
            switch (excel)
            {
                case "XLS":
                    Response.ContentType = "application/vnd.ms-excel";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" +
                         "Danh_Sach_Cac_Dot_BH.xls");
                    ef.SaveXls(Response.OutputStream);
                    break;

                case "XLSX":
                    Response.ContentType = "application/vnd.openxmlformats";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" +
                         "Danh_Sach_Cac_Dot_BH.xlsx");
                    MemoryStream ms = new MemoryStream();
                    ef.SaveXlsx(ms);
                    ms.WriteTo(Response.OutputStream);
                    break;
            }
            Response.End();
        }

        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            GetData("2");
            export();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            GetData("2");
        }

        protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            string id = GridView1.Rows[e.NewSelectedIndex].Cells[1].Text;
            Response.Redirect("DanhSachBHTN.aspx?Id=" + id);
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            GetData("2");
            export();
        }

        protected void btnPrintCard_Click(object sender, EventArgs e)
        {

        }

    }
}